<template>
  <div>
    <search-bar @onSearch="onSearch" />
    <div class="btns">
      <el-button @click="$router.push('/itemAdd')" type="primary">单个新增</el-button>
      <el-upload action="#" accept=".xlsx, .xls" :before-upload="readExcel">
        <el-button type="success">批量导入</el-button>
      </el-upload>
      <el-button @click="exportItemTpl" type="danger">下载模板</el-button>
    </div>
    <el-table :data="items" style="width: 100%" height="500px">
      <el-table-column prop="itemName" label="商品名字" />
      <el-table-column prop="price" label="商品价格" />
      <el-table-column prop="desc" label="商品描述">
        <template #default="{ row }">
          <el-tooltip class="box-item" effect="dark" placement="bottom">
            <template #content>
              <div style="width: 500px">
                {{ row.desc }}
              </div>
            </template>
            <div>{{ row.desc.substr(0, 15) + '...' }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="sale" label="销量">
        <template #default="{ row }">
          <el-tag :color="row.sale > 500 ? 'red' : 'green'">{{ row.sale }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="onsale" label="上下架">
        <template #default="{ row }">
          <div>
            <el-switch v-model="row.onsale" inline-prompt active-text="上架" @change="switchSaleState(row.id, row.onsale)"
              inactive-text="下架" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createAt" label="上架时间" />
      <el-table-column prop="thumb" label="封面图片">
        <template #default="{ row }">
          <div>
            <el-image style="width: 50px; height: 50px" :src="row.thumb" :zoom-rate="1.2" :preview-src-list="row.imgLists"
              preview-teleported fit="cover" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <div>
            <el-button @click="enterUpdate(row.id)" type="primary">编辑</el-button>
            <el-button type="danger" @click="delItem(row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:page-size="pageSize" v-model:current-page="page" layout="prev, pager, next, jumper, sizes"
      :total="total" />
  </div>
</template>

<script>
import { fetchItems, addItems, delItem } from '@a/itemLists'
import { updateItem } from '@/api/itemUpdate'
import SearchBar from '@/components/SearchBar.vue'
import { read, utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'itemLists',
  data () {
    return {
      // 搜索参数
      searchParams: {
        key: '',
        start: '',
        end: ''
      },
      // 分页参数
      page: 1,
      pageSize: 10,
      items: [],
      total: 0
    }
  },
  methods: {
    delItem (id) {
      // 删除商品
      this.$confirm('此操作会彻底删除商品,继续吗?', '删除').then(() => {
        delItem(id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            })
            this.$router.go(0)
          }
        })
      })
    },
    enterUpdate (id) {
      // 跳转到修改商品页
      this.$router.push({
        path: '/itemUpdate',
        query: {
          id
        }
      })
    },
    readExcel (file) {
      const fd = new FileReader()
      fd.readAsArrayBuffer(file)
      fd.onload = () => {
        const wb = read(fd.result)
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        const _data = data.map(item => {
          return {
            itemName: item.商品名,
            price: item.商品价格,
            desc: item.商品描述
          }
        })
        // 请求批量添加商品的接口
        addItems({
          items: _data
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            })
            this.$router.go(0)
          }
        })
      }
      return false
    },
    exportItemTpl () {
      // 点击导出excel
      // 导出数据
      const data = [
        {
          商品名: '商品1',
          商品价格: 10,
          商品描述: '这是描述'
        }
      ]
      const ws = utils.json_to_sheet(data)
      const wb = utils.book_new()
      utils.book_append_sheet(wb, ws, 'Data')
      writeFileXLSX(wb, '商品excel模板.xlsx')
    },
    onSearch (searchParams) {
      this.searchParams = searchParams
      this.fetchItems()
    },
    switchSaleState (id, onsale) {
      // 行内修改商品选中状态
      updateItem({
        id,
        onsale
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            duration: 2000,
            onClose: () => {
              this.$router.go(0)
            }
          })
        }
      })
    },
    // 请求商品列表
    fetchItems () {
      fetchItems({
        ...this.searchParams,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        if (res.data.code === 200) {
          this.items = res.data.data.lists
          this.total = res.data.data.total
        }
      })
    }
  },
  watch: {
    // 监听当前页 和 一页多少条  重新请求列表
    page () {
      this.fetchItems()
    },
    pageSize () {
      this.fetchItems()
    }
  },
  created () {
    this.fetchItems()
  },
  components: {
    SearchBar
  }
}
</script>

<style lang="scss" scoped>
.btns {
  display: flex;
}
</style>
